# -*- coding:utf-8 -*-

import time
from  socket import *
import json


HOST = '127.0.0.1'
PORT = 21567
ADDR = (HOST,PORT)
BUFSIZE = 1024
class Client:

    def __init__(self):
        self.tcpClient = socket(AF_INET,SOCK_STREAM)
        self.pingTime = 0
        self.id = 0
        self.sleepTime = 0
        pass


    def send_json(self,obj):
        string = json.dumps(obj)
        self.send(string)

    def send(self,string):
        self.tcpClient.sendall(string.encode('utf-8'))
        # self.tcpClient.send()
        print("{} : {} >> {} ".format(time.ctime(),self.id,string))

    def start(self):
        self.tcpClient.connect(ADDR)
        if self.connect_handshake() == False:
            return

        while True:
            # self.send_other()
            # user_input = input("cmd:")
            # if user_input == "close":
            #     self.send_close()
            # if user_input == "send":
            #     self.send_other()
            # if user_input == "ping":
            #     self.send_ping()

            data = self.tcpClient.recv(BUFSIZE)
            rString = data.decode('utf-8')
            print("<<", rString)
            msgs = json.loads(rString)
            for msg in msgs:
                msgObj = json.loads(msg)
                if self.handle(msgObj) == False:
                    break



            # time.sleep(self.sleepTime)
            # self.pingTime += 1
            # if self.pingTime == 10000:
            #     self.send_close()
            #     break
        print("connect end")


    def connect_handshake(self):
        self.send_info()
        data = self.tcpClient.recv(BUFSIZE)
        print("<< ",data)
        rString = data.decode('utf-8')
        msg = json.loads(rString)[0]
        msgObj = json.loads(msg)
        if "ok" == msgObj["cmd"]:
            return True
        return False


    def handle(self,msg):
        cmd = msg['cmd']
        if cmd == 'close':
            return False
        return  True


    def send_other(self):
        to = 0
        if int(self.id) == 1:
            to = 2
        else:
            to = 1
        send = {
            "cmd" : "send",
            "id"  : str(to),
            "msg" : "haha"
        }
        self.send_json(send)


    def send_ping(self):
        info = {
            "cmd":"ping"
        }
        self.send_json(info)
        print("send ping {}".format(self.pingTime))

    def send_info(self):
        info = {
                "cmd":"info",
                "id":self.id
                }
        self.send_json(info)


    def send_close(self):
        cmd = {'cmd':"close"}
        self.send_json(cmd)


    def close(self):
        self.tcpClient.close()